package com.example.android.commitcontent.ime.cores.base;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import butterknife.ButterKnife;

public abstract class BaseFragment extends Fragment {

    private boolean isLoaded = false;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (!(getActivity() instanceof BaseActivity))
            throw new RuntimeException(getActivity().getClass().getName() + " must extends " + BaseActivity.class.getName());
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View layout = inflater.inflate(setLayoutRes(), container, false);
        ButterKnife.bind(this, layout);
        return layout;
    }

    protected abstract int setLayoutRes();

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        initView();
        initData();
        startLazyLoadData();
    }

    private void startLazyLoadData() {
        if (getUserVisibleHint() && getView() != null) {
            if (!isLoaded) {
                lazyLoadData();
                isLoaded = true;
            }
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        startLazyLoadData();
    }

    protected abstract void initView();

    protected abstract void initData();

    protected void lazyLoadData() {
    }

    protected void showLoadingDialog() {
        showLoadingDialog(null, null);
    }

    public void showLoadingDialog(@Nullable String title, @Nullable String message) {
        if (getActivity() != null)
            ((BaseActivity) getActivity()).showLoadingDialog(title, message);
    }

    protected void dismissLoadingDialog() {
        if (getActivity() != null)
            ((BaseActivity) getActivity()).dismissLoadingDialog();
    }
}
